/**
 * @Date:   2018-09-10T16:06:23+08:00
 * @Filename: fex.js
 * @Last modified time: 2018-09-22T00:37:13+08:00
 */

const FCoin = require('node-fcoin')

class Fex {

  constructor(config, name, digits) {
    this.config = config
    this._name = name
    this.fcoin = {}
    this._digits = digits || 2
    this._debug = false
  }

  set debug(debug) {
    this._debug = debug
  }

  get symbol() {
    return this._name;
  }

  set symbol(value) {
    this._name = value
  }

  get digits() {
    return this._digits
  }

  set digits(value) {
    this._digits = value
  }

  init() {
    if (!this._name) {
      let err = new Error('请输入订阅的币种')
      throw err
    }
    this.fcoin = new FCoin(this.config)
    this.fcoin.connectWebSocket()
  }

  getTicker(symbol = '', digits = 2) {
    this.fcoin.subscribeTicker(symbol || this.symbol)
    this.fcoin.on('ticker', data => {
      return new Promise((resolve, reject) => {
        if (data) {
          data = data.ticker
          let _drop = ((data[0] - data[6]) / 100).toString()
          _drop = _drop.substr(0, _drop.indexOf('.') + digits + 1)
          let _ticker = {
            'last_price': data[0],
            'last_volume': data[1],
            'maximum_price': data[2],
            'maximum_purchase': data[3],
            'minimum_price': data[4],
            'minimum_charge': data[5],
            '24st_price': data[6],
            '24st_highest_price': data[7],
            '24st_smallest_price': data[8],
            '24st_benchmark_volume': data[9],
            '24st_denominated_volume': data[10],
            '24st_drop': (_drop >= 0) ? `+${_drop}%` : `${_drop}%`
          }
          if (this._debug) {
            console.log(`The ticker of ${this.symbol}: ${JSON.stringify(_ticker)}\n`)
          }
          resolve(_ticker)
        } else {
          reject('error')
        }
      })
      this.fcoin.disconnectWebSocket()
    })
  }

  getDepth(symbol = '', level = 'L20') {
    symbol = symbol || this.symbol
    this.fcoin.subscribeDepth(symbol, level)
    this.fcoin.on('depth', data => {
      let _result = {
        bids: [],
        asks: []
      }
      return new Promise((resolve, reject) => {
        if (data.depth) {
          let ask = data.depth.asks
          let bids = data.depth.bids

          if (ask.length > 0) {
            _result.asks = makedData.call(this, ask)
          }
          if (bids.length > 0) {
            _result.bids = makedData.call(this, bids)
          }
          if (this._debug) {
            console.log(`The depth of ${this.symbol}: ${JSON.stringify(_result)}\n`)
          }
          resolve(_result)
        } else {
          reject('error')
        }
      })
      this.fcoin.disconnectWebSocket()
    })
  }

  getTrade(symbol = '') {
    this.fcoin.subscribeTrade(symbol || this.symbol)
    this.fcoin.on('trade', data => {
      return new Promise((resolve, reject) => {
        if (data) {
          if (this._debug) {
            console.log(`The trade of ${this.symbol}: ${JSON.stringify(data)}`)
          }
          resolve(data.trade)
        } else {
          reject('error')
        }
      })
      this.fcoin.disconnectWebSocket()
    })
  }
}
/**
 * [makedData 组织深度数据]
 * @param  {[type]} data [数据]
 * @return {[type]}      [数据]
 */
function makedData(data) {
  let _item = []
  let _sub = 0
  for (var i = 0; i < data.length; i += 2) {
    _sub += data[i + 1]
    _item.push({
      price: data[i],
      num: data[i + 1],
      amount: digits.call(this, _sub)
    })
  }
  return _item
}
/**
 * [digits 保留小数位精确位数]
 * @param  {[type]} str [description]
 * @return {[type]}     [description]
 */
function digits(str) {
  let digits = this.digits + 1
  if (typeof(str) !== 'String') {
    str = str.toString()
  }
  return parseFloat(str.substr(0, str.indexOf('.') + digits))
}

// let fex = new Fex({
//   key: 'b74be4a2eef8421dbaf2360a139baf4e',
//   secret: 'bda1f1f2063a43429f568a64ecf01d55'
// })
// fex.symbol = 'btcusdt'  // 订阅币种特征
// fex.digits = 5
// fex.debug = true
// fex.init()              // 初始化
// fex.getTicker()
// // fex.getTrade()
// fex.getDepth()
